package com.meida.module.bus.provider.handler;

import com.meida.common.base.entity.EntityMap;
import com.meida.common.base.utils.FlymeUtils;
import com.meida.common.mybatis.interceptor.PageInterceptor;
import com.meida.common.mybatis.model.PageParams;
import com.meida.common.mybatis.query.CriteriaQuery;
import com.meida.module.admin.client.entity.BaseUser;
import com.meida.module.admin.provider.service.BaseUserService;
import com.meida.module.bus.client.entity.BusAfterservice;
import com.meida.module.bus.client.entity.BusOrder;
import com.meida.module.bus.client.entity.BusReason;
import com.meida.module.user.client.entity.AppUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 后台订单售后列表
 */
@Component
public class BusAfterServicePageListHandler implements PageInterceptor<BusAfterservice> {

    @Autowired
    private BaseUserService baseUserService;

    @Override
    public void prepare(CriteriaQuery<BusAfterservice> cq, PageParams pageParams, EntityMap params) {
        cq.clear();
        String beginDate = params.get("beginDate");
        String endDate = params.get("endDate");
        cq.select(BusAfterservice.class, "afterServiceId", "orderId", "reasonId", "afterDescribe", "state", "reviewerId", "auditMind", "auditTime", "createTime");
        cq.select(AppUser.class, "userName", "nickName", "mobile");
        cq.select(BusOrder.class, "orderNo");
        cq.select(BusReason.class, "reasonTitle");
        cq.eq(BusAfterservice.class, "afterServiceId");
        cq.eq(BusAfterservice.class, "state");
        cq.eq(BusAfterservice.class, "userId");
        cq.eq(BusAfterservice.class, "orderId");
        cq.like(BusOrder.class, "orderNo");
        cq.like(AppUser.class, "userName");
        cq.like(AppUser.class, "nickName");
        cq.like(AppUser.class, "mobile");
        cq.ge("DATE_FORMAT(afterservice.createTime,'%Y-%m-%d')", beginDate);
        cq.le("DATE_FORMAT(afterservice.createTime,'%Y-%m-%d')", endDate);
        cq.createJoin(BusOrder.class).setMainField("orderId").setJoinField("orderId");
        cq.createJoin(BusReason.class).setMainField("reasonId").setJoinField("reasonId");
        cq.createJoin(AppUser.class).setMainField("userId").setJoinField("userId");
    }

    @Override
    public void complete(CriteriaQuery<BusAfterservice> cq, List<EntityMap> result, EntityMap extra) {
        result.forEach(entityMap -> {
            Long reviewerId = entityMap.getLong("reviewerId");
            BaseUser baseUser = baseUserService.getById(reviewerId);
            entityMap.put("reviewerUserName", "");
            if (FlymeUtils.isNotEmpty(baseUser)) {
                entityMap.put("reviewerUserName", baseUser.getUserName());
            }
        });

    }

}
